import { Component, OnInit } from '@angular/core';
import { ActionSheetController,AlertController,ToastController  } from '@ionic/angular';
import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import { CommonResponse,VerificationType,ToastColor,CommonService,AutoLoginType } from '@services/common-service.service';
import { AuthTokenService } from '@services/auth-token.service'
import { DefaultLanguageService } from '@services/default-language.service';
import {TranslateService} from '@ngx-translate/core';
import { HttpErrorResponse } from '@angular/common/http';
@Component({
  selector: 'app-mobile-number',
  templateUrl: './mobile-number.page.html',
  styleUrls: ['./mobile-number.page.scss'],
})
export class MobileNumberPage implements OnInit {

  private i18n:any = {};

  public mobileNumber:string;

  constructor(
    private route: ActivatedRoute,
    private actionSheetController: ActionSheetController,
    private alertController: AlertController,
    private faio:FingerprintAIO,
    private toastController: ToastController,
    private router:Router,
    private commonService:CommonService,
    private authTokenService:AuthTokenService,
    private defaultLanguageService:DefaultLanguageService,
    private translate:TranslateService) { }

  ngOnInit() {
    this.initLanguage();
    this.getMobileNumber();
  }

  initLanguage(){
    this.i18n = this.commonService.initTranslate(['myAccount.setting.accountScurity.mobileNumberFunction']); 
  }

  getMobileNumber(){
    this.route.queryParams.subscribe((data)=>{
      if(!data.mobileNumber){return false;}
      this.commonService.getMobileNumber(data.mobileNumber).subscribe((response:CommonResponse)=>{
        if(response.isSuccess){
          this.mobileNumber = response.responseBody;
        }
      })
		})
  }

  async verifyMobile(){
    if(!this.mobileNumber){
      return false;
    }
    const actionSheet = await this.actionSheetController.create({
      header: '',
      keyboardClose:true,
      buttons: [
      {
        text: this.i18n.touchId,
        role: '',
        icon: '',
        handler: () => {
          this.checkFingerprintEnable();
        }
      },
      {
        text: this.i18n.loginPwd,
        role: '',
        icon: '',
        handler: () => {
          this.presentPasswordPrompt();
        }
      }, 
      {
        text: this.i18n.cancel,
        icon: '',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }
      ]
    });
    await actionSheet.present();
  }

  checkFingerprintEnable(){
    let appUserId = this.authTokenService.getAppUserId();
    let fingerPrintLogin = false;
    this.commonService.getAppUser(appUserId).subscribe((response:CommonResponse)=>{
      if(response.isSuccess){
        let fingerPrintLogin = response.responseBody.fingerPrintLogin;
        if(fingerPrintLogin){
          this.presentFingerprintPrompt();
        }else{
          this.openEnableFingerprintPrompt();
        }
      }
    });
  }

  async openEnableFingerprintPrompt(){
    const alert = await this.alertController.create({
      header: 'Your Face ID/Touch ID is not available. Please open Face ID/Touch ID first.',
      buttons: [
        {
          text: this.i18n.cancel,
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            //console.log('Confirm Cancel');
          }
        }, {
          text: this.i18n.confirm,
          handler: (data) => {
            this.router.navigate(['tabs/myAccount/setting/fingerprint-setup']);
          }
        }
      ]
    });
    await alert.present();
  }

  presentFingerprintPrompt() {
    this.faio.show({
        title: '',
        fallbackButtonTitle: 'Use Backup',
        disableBackup:true,
    }).then((result: any) => {
      if(result == "biometric_success"){
        this.router.navigate(['/tabs/myAccount/setting/account-security/mobile-number/mobile-number-edit']);
      }else {
        this.commonService.commonToast(ToastColor.warning);
      }
    }).catch((error: any) => {
      //this.commonService.commonToast(ToastColor.warning);
    });
  }

  async presentPasswordPrompt() {
    const alert = await this.alertController.create({
      header: this.i18n.please_enter_login_pwd,
      inputs: [
        {
          name: "password",
          type: 'password',
          placeholder: this.i18n.password
        }
      ],
      buttons: [
        {
          text: this.i18n.cancel,
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            //console.log('Confirm Cancel');
          }
        }, {
          text: this.i18n.confirm,
          handler: (data) => {
            if(!data.password){
              return false;
            }
            this.commonService.checkPassword(data.password).subscribe((response:CommonResponse) => {
              if(response.isSuccess && response.responseBody.isPass){
                this.router.navigate(['/tabs/myAccount/setting/account-security/mobile-number/mobile-number-edit']);
              }else{  
                this.commonService.commonToast(ToastColor.warning,this.i18n.passwordIncorrent);
              }
            },
            (errorResponse:HttpErrorResponse)=>{
              this.commonService.errorRespCommonToast(errorResponse,this.i18n);
            });
          }
        }
      ]
    });
    await alert.present();
  }

  async presentFaceIdPrompt() {
    const alert = await this.alertController.create({
      header: 'Your Face ID is not available. Please open Face ID first.',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            console.log('Confirm Cancel');
          }
        }, {
          text: 'Confirm',
          handler: () => {
            console.log('Confirm Ok');
          }
        }
      ]
    });
    await alert.present();
  }


}
